package com.mdl.springmvc.handler.handlers;

import com.mdl.springmvc.handler.dao.EmployeeDao;
import com.mdl.springmvc.handler.entity.Employee;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.Map;


/**
 * @Desc
 * @Author madengling
 * @Time 2020/11/6 10:07
 */
@Controller
@RequestMapping("/test")
public class TestHandler {
    private static Logger logger = Logger.getLogger(TestHandler.class);

    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private ResourceBundleMessageSource messageSource;

    @RequestMapping("testSimpleMappingExceptionResolver")
    public String testSimpleMappingExceptionResolver(@RequestParam("i")int i){
        String [] vals = new String[10];
        logger.info(vals[i]);
        return "success";
    }

    @RequestMapping(value = "testDefaultHandlerExceptionResolver",method = RequestMethod.POST)
    public String testDefaultHandlerExceptionResolver(){
        logger.info("testDefaultHandlerExceptionResolver...");
        return "success";
    }

    @ResponseStatus(value = HttpStatus.NOT_FOUND,reason = "测试")
    @RequestMapping("testResponseStatusExceptionResolver")
    public String testResponseStatusExceptionResolver(@RequestParam("i")int i){
        if(i == 13){
            throw new UserNameNotMatchPasswordException();
        }
        logger.info("testResponseStatusExceptionResolver...");
        return "success";
    }

//    @ExceptionHandler({RuntimeException.class})
//    public ModelAndView handlerArithmeticException2(Exception ex){
//        logger.error("[出异常了]："+ex);
//        ModelAndView mv = new ModelAndView("error");
//        mv.addObject("exception", ex);
//        return mv;
//    }

    /**
     * 1.在@ExceptionHandler方法的入参中可以加入Exception类型的参数，该参数即对应发生的异常对象
     * 2.@ExceptionHandler方法的入参中不能传入Map。若希望把异常信息传到页面上，需要使用ModelAndView作为返回值
     * 3.@ExceptionHandler方法标记的异常有优先级的问题。
     * 4.@ControllerAdvice：如果在当前Handler中找不到@ExceptionHandler方法来处理当前方法出现的异常，
     * 则将去@ControllerAdvice标记的类中查找@ExceptionHandler标记的方法来处理异常。
     * @return
     */
//    @ExceptionHandler({ArithmeticException.class})
//    public ModelAndView handlerArithmeticException(Exception ex){
//        logger.error("出异常了："+ex);
//        ModelAndView mv = new ModelAndView("error");
//        mv.addObject("exception", ex);
//        return mv;
//    }

    @RequestMapping("/testExceptionHandlerExceptionResolver")
    public String testExceptionHandlerExceptionResolver(@RequestParam("i") Integer i){
        logger.info("result: "+(10/i));
        return "success";
    }

    //    MultipartResolver
    @RequestMapping("/testFileUpload")
    public String testFileUpload(@RequestParam("desc")String desc,
                                 @RequestParam("file")MultipartFile file) throws IOException {
        logger.info("desc"+desc);
        logger.info("OriginalFilename"+file.getOriginalFilename());
        logger.info("InputStream"+file.getInputStream());
        return "success";
    }

    @RequestMapping("/i18n")
    public String testI18n(Locale lccale){
        String val = messageSource.getMessage("i18n.username",null,lccale);
        logger.info(val);
        return "i18n";
    }

    @RequestMapping("/testResponseEntity")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        byte[] body = null;
        ServletContext servletContext = session.getServletContext();
        InputStream in = servletContext.getResourceAsStream("/files/abc.txt");
        body = new byte[in.available()];
        in.read(body);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition","attachment;filename=abc.txt");

        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> response = new ResponseEntity<>(body,headers,statusCode);
        return response;
    }

    @ResponseBody
    @RequestMapping("/testHttpMessageConverter")
    public String testHttpMessageConverter(@RequestBody String body){
        logger.info(body);
        return "HelloWorld!" + new Date();
    }

    @ResponseBody
    @RequestMapping("/testJson")
    public Collection<Employee> testJson(){
        return employeeDao.getAll();
    }

    @RequestMapping("chaoshi")
    public void chaoshi(String areacode,String para,String projId,String jkbm){
        logger.info("areacode={"+areacode+"},para={"+para+"},projId={"+projId+"},jkbm={"+jkbm+"}");
        try {
//            HttpMessageConverter
//            HttpInputMessage
//            HttpOutputMessage
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("testConversionServiceConverer")
    public String testCOnverter(@RequestParam("employee")Employee employee){
        logger.info("save Employee...");
        employeeDao.save(employee);
        return "redirect:/emps";
    }
}
